<!-- src/components/ParticleBackground.vue -->
<template>
  <canvas ref="canvas" class="particle-background"></canvas>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const canvas = ref(null)
let animationFrame = null
const particles = ref([])
const particleCount = 80
let debounceTimer = null

// 防抖函数
const debounce = (func, delay = 200) => {
  return function() {
    clearTimeout(debounceTimer)
    debounceTimer = setTimeout(() => {
      func.apply(this, arguments)
    }, delay)
  }
}

const initParticles = () => {
  const ctx = canvas.value.getContext('2d')
  
  // 清空画布
  ctx.clearRect(0, 0, canvas.value.width, canvas.value.height)
  
  // 重置画布尺寸
  canvas.value.width = canvas.value.offsetWidth
  canvas.value.height = canvas.value.offsetHeight
  
  // 清空现有粒子
  particles.value = []
  
  // 创建新粒子
  for (let i = 0; i < particleCount; i++) {
    particles.value.push({
      x: Math.random() * canvas.value.width,
      y: Math.random() * canvas.value.height,
      size: Math.random() * 3 + 1,
      speedX: Math.random() * 1 - 0.5,
      speedY: Math.random() * 1 - 0.5,
      color: `rgba(255, 255, 255, ${Math.random() * 0.4 + 0.1})`
    })
  }

  const animate = () => {
    ctx.clearRect(0, 0, canvas.value.width, canvas.value.height)
    
    // 更新和绘制粒子
    particles.value.forEach(p => {
      p.x += p.speedX
      p.y += p.speedY
      
      // 边界检查
      if (p.x < 0 || p.x > canvas.value.width) p.speedX *= -1
      if (p.y < 0 || p.y > canvas.value.height) p.speedY *= -1
      
      // 绘制粒子
      ctx.beginPath()
      ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2)
      ctx.fillStyle = p.color
      ctx.fill()
    })
    
    // 绘制粒子间的连线
    for (let i = 0; i < particles.value.length; i++) {
      for (let j = i + 1; j < particles.value.length; j++) {
        const dx = particles.value[i].x - particles.value[j].x
        const dy = particles.value[i].y - particles.value[j].y
        const distance = Math.sqrt(dx * dx + dy * dy)
        
        if (distance < 100) {
          ctx.beginPath()
          ctx.strokeStyle = `rgba(255, 255, 255, ${0.2 - distance / 500})`
          ctx.lineWidth = 0.5
          ctx.moveTo(particles.value[i].x, particles.value[i].y)
          ctx.lineTo(particles.value[j].x, particles.value[j].y)
          ctx.stroke()
        }
      }
    }
    
    animationFrame = requestAnimationFrame(animate)
  }

  // 停止当前动画
  cancelAnimationFrame(animationFrame)
  animate()
}

// 防抖后的resize处理函数
const handleResize = debounce(() => {
  initParticles()
})

onMounted(() => {
  initParticles()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  cancelAnimationFrame(animationFrame)
  window.removeEventListener('resize', handleResize)
  clearTimeout(debounceTimer)
})
</script>

<style scoped>
.particle-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
</style>